package com.wlps.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlps.contant.Contant;
import com.wlps.entity.SysPermission;
import com.wlps.entity.SysRolePermission;
import com.wlps.result.ResultUtils;
import com.wlps.result.ResultVo;
import com.wlps.result.StatusCode;
import com.wlps.service.ISysPermissionService;
import com.wlps.service.ISysRolePermissionService;
import com.wlps.vo.TreeList;
import com.wlps.vo.TreeVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限表（菜单表）（sys_permission） 前端控制器
 * </p>
 *
 * @author ZWYZY
 * @since 2020-07-30
 */
@Slf4j
@RestController
@RequestMapping("/api/permission")
@Api(tags = "系统管理-权限管理", description = "")
public class        SysPermissionController {
    @Autowired
    public ISysPermissionService permissionService;

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 获取菜单列表
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getMenuList", method = RequestMethod.POST)
    public ResultVo getMenuList() {

        QueryWrapper<SysPermission> query = new QueryWrapper<>();
        query.lambda().orderByAsc(SysPermission::getOrderNum);
        List<SysPermission> list = permissionService.list(query);
        List<SysPermission> menuList = null;
        if (!list.isEmpty()) {
            menuList = makeTree(list, 0L);
        }
        return ResultUtils.success("成功", StatusCode.SUCCESS_CODE, menuList);
    }

    /**
     * 组装树
     *
     * @param menuList
     * @param pId
     * @return
     */
    private static List<SysPermission> makeTree(List<SysPermission> menuList, Long pId) {

//子类
        List<SysPermission> children = menuList.stream().filter(x -> x.getParentId() ==
                pId).collect(Collectors.toList());
//后辈中的非子类
        List<SysPermission> successor = menuList.stream().filter(x -> x.getParentId() !=
                pId).collect(Collectors.toList());
        if (children.size() > 0) {
            children.forEach(x ->
                    {
                        if (successor.size() > 0) {
                            makeTree(successor, x.getId()).forEach(
                                    y -> x.getChildren().add(y)
                            );
                        }
                    }
            );
        }
        return children;
    }

    /**
     * 新增权限
     */
    @RequestMapping(value = "/addPermission", method = RequestMethod.POST)
    public ResultVo addPermission(@RequestBody SysPermission permission) {
        permissionService.save(permission);
        return ResultUtils.success("新增成功");
    }

    /**
     * 新增权限，上级菜单树
     *
     * @return
     */
    @RequestMapping(value = "/getParentTree", method = RequestMethod.POST)
    public ResultVo getParentTree(@RequestParam Long id) {
        List<SysPermission> roleList;
        if (redisTemplate.hasKey(Contant.ROLEPERMISSION_KEY+id)) {
            roleList = (List<SysPermission>) redisTemplate.opsForValue().get(Contant.ROLEPERMISSION_KEY+id);
        } else {
            roleList = permissionService.findByRoleId(id);

        }
        HashMap<SysPermission, Integer> hashMap = new HashMap<>();
        for (SysPermission sysPermission : roleList
        ) {
            hashMap.put(sysPermission, 1);
        }
        QueryWrapper<SysPermission> query = new QueryWrapper<>();
        query.lambda().eq(SysPermission::getType, "0").or().eq(SysPermission::getType, "1");
        List<SysPermission> list = permissionService.list(query);
        List<TreeVo> listTree = new ArrayList<>();


        if (list.size() > 0) {
            for (SysPermission p : list) {
                if (p != null) {
                    TreeVo tree = new TreeVo();
                    tree.setId(p.getId());
                    tree.setPid(p.getParentId());
                    tree.setName(p.getLabel());
                    tree.setOpen(true);
                    if (hashMap.containsKey(p)) {
                        tree.setChecked(true);

                    } else {
                        tree.setChecked(false);
                    }
                    listTree.add(tree);
                }

            }
        }
        return ResultUtils.success("成功", listTree);
    }

    @Autowired
    ISysRolePermissionService sysRolePermissionService;

    @PostMapping("/saveParentTree")
    public ResultVo saveParentTree(@RequestBody TreeList treeList, @RequestParam Long id) {
        List<SysPermission> roleList;
        if (redisTemplate.hasKey(Contant.ROLEPERMISSION_KEY+id)) {
            roleList = (List<SysPermission>) redisTemplate.opsForValue().get(Contant.ROLEPERMISSION_KEY+id);
        } else {
            roleList = permissionService.findByRoleId(id);

        }

        for (TreeVo treeVo : treeList.getTreeVoList()) {
            long count = roleList.stream().filter(x -> x != null && treeVo.getId().equals(x.getId())).count();

            if (treeVo.getChecked()) {

                if (count == 0) {
                    SysRolePermission sysRolePermission = new SysRolePermission();
                    sysRolePermission.setRoleId(id);
                    sysRolePermission.setPermissionId(treeVo.getId());
                    sysRolePermissionService.save(sysRolePermission);
                }
            } else {
                if (count > 0) {
                    sysRolePermissionService.remove(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getPermissionId, treeVo.getId()).eq(SysRolePermission::getRoleId, id));
                }
            }
        }
        permissionService.findByRoleId(id);
        return new ResultVo("修改权限成功", 200, null);

    }

    /**
     * 根据id查询菜单
     *
     * @param permission
     * @return
     */
    @RequestMapping(value = "getMenuById", method = RequestMethod.POST)
    public ResultVo getMenuById(@RequestBody SysPermission permission) {
        SysPermission menu = permissionService.getById(permission.getId());
        return ResultUtils.success("成功", menu);
    }

    /**
     * 根据id更新权限
     *
     * @param permission
     * @return
     */
    @RequestMapping(value = "/editSave", method = RequestMethod.POST)
    public ResultVo editSave(@RequestBody SysPermission permission) {
        permission.setCreateTime(new Date());
        boolean res = permissionService.updateById(permission);
        if (res) {
            return ResultUtils.success("更新成功");
        } else {
            return ResultUtils.error("更新失败");
        }
    }

    /**
     * 删除权限
     *
     * @return
     */
    @RequestMapping(value = "/deleteEntity", method = RequestMethod.POST)
    public ResultVo deleteEntity(@RequestBody SysPermission permission) {
        boolean b = permissionService.removeById(permission.getId());
        if (b) {
            return ResultUtils.success("删除成功!");
        } else {
            return ResultUtils.error("删除失败!");
        }
    }
}
